//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.apache.flink.sql.parser;

import org.apache.calcite.avatica.util.Casing;
import org.apache.calcite.config.CharLiteralStyle;
import org.apache.calcite.runtime.CalciteContextException;
import org.apache.calcite.sql.*;
import org.apache.calcite.sql.parser.SqlParseException;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.parser.SqlParserUtil;
import org.apache.calcite.sql.type.SqlOperandTypeChecker;
import org.apache.calcite.sql.type.SqlOperandTypeInference;
import org.apache.calcite.sql.type.SqlReturnTypeInference;
import org.apache.calcite.sql.validate.SqlConformance;
import org.apache.flink.calcite.shaded.com.google.common.collect.ImmutableList;
import org.apache.flink.calcite.shaded.com.google.common.collect.ImmutableSet;
import org.apache.flink.calcite.shaded.com.google.common.collect.Iterables;

import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

public abstract class SqlAbstractParserImpl {
    private static final ImmutableSet<String> SQL_92_RESERVED_WORD_SET = ImmutableSet.of("ABSOLUTE", "ACTION", "ADD", "ALL", "ALLOCATE", "ALTER", new String[]{"AND", "ANY", "ARE", "AS", "ASC", "ASSERTION", "AT", "AUTHORIZATION", "AVG", "BEGIN", "BETWEEN", "BIT", "BIT_LENGTH", "BOTH", "BY", "CALL", "CASCADE", "CASCADED", "CASE", "CAST", "CATALOG", "CHAR", "CHARACTER", "CHARACTER_LENGTH", "CHAR_LENGTH", "CHECK", "CLOSE", "COALESCE", "COLLATE", "COLLATION", "COLUMN", "COMMIT", "CONDITION", "CONNECT", "CONNECTION", "CONSTRAINT", "CONSTRAINTS", "CONTAINS", "CONTINUE", "CONVERT", "CORRESPONDING", "COUNT", "CREATE", "CROSS", "CURRENT", "CURRENT_DATE", "CURRENT_PATH", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DATE", "DAY", "DEALLOCATE", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DELETE", "DESC", "DESCRIBE", "DESCRIPTOR", "DETERMINISTIC", "DIAGNOSTICS", "DISCONNECT", "DISTINCT", "DOMAIN", "DOUBLE", "DROP", "ELSE", "END", "ESCAPE", "EXCEPT", "EXCEPTION", "EXEC", "EXECUTE", "EXISTS", "EXTERNAL", "EXTRACT", "FALSE", "FETCH", "FIRST", "FLOAT", "FOR", "FOREIGN", "FOUND", "FROM", "FULL", "FUNCTION", "GET", "GLOBAL", "GO", "GOTO", "GRANT", "GROUP", "HAVING", "HOUR", "IDENTITY", "IMMEDIATE", "IN", "INADD", "INDICATOR", "INITIALLY", "INNER", "INOUT", "INPUT", "INSENSITIVE", "INSERT", "INT", "INTEGER", "INTERSECT", "INTERVAL", "INTO", "IS", "ISOLATION", "JOIN", "KEY", "LANGUAGE", "LAST", "LEADING", "LEFT", "LEVEL", "LIKE", "LOCAL", "LOWER", "MATCH", "MAX", "MIN", "MINUTE", "MODULE", "MONTH", "NAMES", "NATIONAL", "NATURAL", "NCHAR", "NEXT", "NO", "NOT", "NULL", "NULLIF", "NUMERIC", "OCTET_LENGTH", "OF", "ON", "ONLY", "OPEN", "OPTION", "OR", "ORDER", "OUT", "OUTADD", "OUTER", "OUTPUT", "OVERLAPS", "PAD", "PARAMETER", "PARTIAL", "PATH", "POSITION", "PRECISION", "PREPARE", "PRESERVE", "PRIMARY", "PRIOR", "PRIVILEGES", "PROCEDURE", "PUBLIC", "READ", "REAL", "REFERENCES", "RELATIVE", "RESTRICT", "RETURN", "RETURNS", "REVOKE", "RIGHT", "ROLLBACK", "ROUTINE", "ROWS", "SCHEMA", "SCROLL", "SECOND", "SECTION", "SELECT", "SESSION", "SESSION_USER", "SET", "SIZE", "SMALLINT", "SOME", "SPACE", "SPECIFIC", "SQL", "SQLCODE", "SQLERROR", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "SUBSTRING", "SUM", "SYSTEM_USER", "TABLE", "TEMPORARY", "THEN", "TIME", "TIMESTAMP", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TO", "TRAILING", "TRANSACTION", "TRANSLATE", "TRANSLATION", "TRIM", "TRUE", "UNION", "UNIQUE", "UNKNOWN", "UPDATE", "UPPER", "USAGE", "USER", "USING", "VALUE", "VALUES", "VARCHAR", "VARYING", "VIEW", "WHEN", "WHENEVER", "WHERE", "WITH", "WORK", "WRITE", "YEAR", "ZONE"});
    protected int nDynamicParams;
    protected String originalSql;
    protected final List<CalciteContextException> warnings = new ArrayList();

    public SqlAbstractParserImpl() {
    }

    public static Set<String> getSql92ReservedWords() {
        return SQL_92_RESERVED_WORD_SET;
    }

    protected SqlCall createCall(SqlIdentifier funName, SqlParserPos pos, SqlFunctionCategory funcType, SqlLiteral functionQualifier, Iterable<? extends SqlNode> operands) {
        return this.createCall(funName, pos, funcType, functionQualifier, (SqlNode[])Iterables.toArray(operands, SqlNode.class));
    }

    protected SqlCall createCall(SqlIdentifier funName, SqlParserPos pos, SqlFunctionCategory funcType, SqlLiteral functionQualifier, SqlNode[] operands) {
        SqlOperator fun = new SqlUnresolvedFunction(funName, (SqlReturnTypeInference)null, (SqlOperandTypeInference)null, (SqlOperandTypeChecker)null, (List)null, funcType);
        return ((SqlOperator)fun).createCall(functionQualifier, pos, operands);
    }

    public abstract Metadata getMetadata();

    public abstract SqlParseException normalizeException(Throwable var1);

    protected abstract SqlParserPos getPos() throws Exception;

    public abstract void ReInit(Reader var1);

    public abstract SqlNode parseSqlExpressionEof() throws Exception;

    public abstract SqlNode parseSqlStmtEof() throws Exception;

    public abstract SqlNodeList parseSqlStmtList() throws Exception;

    public abstract void setTabSize(int var1);

    public abstract void setQuotedCasing(Casing var1);

    public abstract void setUnquotedCasing(Casing var1);

    public abstract void setIdentifierMaxLength(int var1);

    public abstract void setConformance(SqlConformance var1);

    public void setOriginalSql(String originalSql) {
        this.originalSql = originalSql;
    }

    public String getOriginalSql() {
        return this.originalSql;
    }

    public abstract void switchTo(LexicalState var1);

    public static class MetadataImpl implements Metadata {
        private final Set<String> reservedFunctionNames = new HashSet();
        private final Set<String> contextVariableNames = new HashSet();
        private final Set<String> nonReservedKeyWordSet = new HashSet();
        private final SortedSet<String> tokenSet = new TreeSet();
        private final List<String> tokenList;
        private final Set<String> reservedWords = new HashSet();
        private final String sql92ReservedWords;

        public MetadataImpl(SqlAbstractParserImpl sqlParser) {
            this.initList(sqlParser, this.reservedFunctionNames, "ReservedFunctionName");
            this.initList(sqlParser, this.contextVariableNames, "ContextVariable");
            this.initList(sqlParser, this.nonReservedKeyWordSet, "NonReservedKeyWord");
            this.tokenList = ImmutableList.copyOf(this.tokenSet);
            this.sql92ReservedWords = this.constructSql92ReservedWordList();
            Set<String> reservedWordSet = new TreeSet();
            reservedWordSet.addAll(this.tokenSet);
            reservedWordSet.removeAll(this.nonReservedKeyWordSet);
            this.reservedWords.addAll(reservedWordSet);
        }

        private void initList(SqlAbstractParserImpl parserImpl, Set<String> keywords, String name) {
            parserImpl.ReInit(new StringReader("1"));

            try {
                Object o = this.virtualCall(parserImpl, name);
                throw new AssertionError("expected call to fail, got " + o);
            } catch (SqlParseException var14) {
                String[] tokenImages = var14.getTokenImages();
                int var8;
                if (this.tokenSet.isEmpty()) {
                    String[] var6 = tokenImages;
                    int var7 = tokenImages.length;

                    for(var8 = 0; var8 < var7; ++var8) {
                        String token = var6[var8];
                        String tokenVal = SqlParserUtil.getTokenVal(token);
                        if (tokenVal != null) {
                            this.tokenSet.add(tokenVal);
                        }
                    }
                }

                int[][] expectedTokenSequences = var14.getExpectedTokenSequences();
                int[][] var19 = expectedTokenSequences;
                var8 = expectedTokenSequences.length;

                for(int var20 = 0; var20 < var8; ++var20) {
                    int[] tokens = var19[var20];

                    assert tokens.length == 1;

                    int tokenId = tokens[0];
                    String token = tokenImages[tokenId];
                    String tokenVal = SqlParserUtil.getTokenVal(token);
                    if (tokenVal != null) {
                        keywords.add(tokenVal);
                    }
                }

            } catch (Throwable var15) {
                Throwable e = var15;
                throw new RuntimeException("While building token lists", e);
            }
        }

        private Object virtualCall(SqlAbstractParserImpl parserImpl, String name) throws Throwable {
            Class<?> clazz = parserImpl.getClass();

            try {
                Method method = clazz.getMethod(name, (Class[])null);
                return method.invoke(parserImpl, (Object[])null);
            } catch (InvocationTargetException var6) {
                InvocationTargetException e = var6;
                Throwable cause = e.getCause();
                throw parserImpl.normalizeException(cause);
            }
        }

        private String constructSql92ReservedWordList() {
            StringBuilder sb = new StringBuilder();
            TreeSet<String> jdbcReservedSet = new TreeSet();
            jdbcReservedSet.addAll(this.tokenSet);
            jdbcReservedSet.removeAll(SqlAbstractParserImpl.SQL_92_RESERVED_WORD_SET);
            jdbcReservedSet.removeAll(this.nonReservedKeyWordSet);
            int j = 0;

            String jdbcReserved;
            for(Iterator var4 = jdbcReservedSet.iterator(); var4.hasNext(); sb.append(jdbcReserved)) {
                jdbcReserved = (String)var4.next();
                if (j++ > 0) {
                    sb.append(",");
                }
            }

            return sb.toString();
        }

        public List<String> getTokens() {
            return this.tokenList;
        }

        public boolean isSql92ReservedWord(String token) {
            return SqlAbstractParserImpl.SQL_92_RESERVED_WORD_SET.contains(token);
        }

        public String getJdbcKeywords() {
            return this.sql92ReservedWords;
        }

        public boolean isKeyword(String token) {
            return this.isNonReservedKeyword(token) || this.isReservedFunctionName(token) || this.isContextVariableName(token) || this.isReservedWord(token);
        }

        public boolean isNonReservedKeyword(String token) {
            return this.nonReservedKeyWordSet.contains(token);
        }

        public boolean isReservedFunctionName(String token) {
            return this.reservedFunctionNames.contains(token);
        }

        public boolean isContextVariableName(String token) {
            return this.contextVariableNames.contains(token);
        }

        public boolean isReservedWord(String token) {
            return this.reservedWords.contains(token);
        }
    }

    public interface Metadata {
        boolean isNonReservedKeyword(String var1);

        boolean isContextVariableName(String var1);

        boolean isReservedFunctionName(String var1);

        boolean isKeyword(String var1);

        boolean isReservedWord(String var1);

        boolean isSql92ReservedWord(String var1);

        String getJdbcKeywords();

        List<String> getTokens();
    }

    public static enum LexicalState {
        DEFAULT,
        DQID,
        BTID,
        BQID;

        private LexicalState() {
        }

        public static LexicalState forConfig(SqlParser.Config config) {
            switch (config.quoting()) {
                case BRACKET:
                    return DEFAULT;
                case DOUBLE_QUOTE:
                    return DQID;
                case BACK_TICK:
                    if (config.conformance().allowHyphenInUnquotedTableName() && config.charLiteralStyles().equals(EnumSet.of(CharLiteralStyle.BQ_SINGLE, CharLiteralStyle.BQ_DOUBLE))) {
                        return BQID;
                    } else if (!config.conformance().allowHyphenInUnquotedTableName() && config.charLiteralStyles().equals(EnumSet.of(CharLiteralStyle.STANDARD))) {
                        return BTID;
                    }
                default:
                    throw new AssertionError(config);
            }
        }
    }

    protected static enum ExprContext {
        ACCEPT_ALL,
        ACCEPT_NONCURSOR,
        ACCEPT_QUERY,
        ACCEPT_NON_QUERY,
        ACCEPT_SUB_QUERY,
        ACCEPT_CURSOR;

        /** @deprecated */
        @Deprecated
        public static final ExprContext ACCEPT_SUBQUERY = ACCEPT_SUB_QUERY;
        /** @deprecated */
        @Deprecated
        public static final ExprContext ACCEPT_NONQUERY = ACCEPT_NON_QUERY;

        private ExprContext() {
        }
    }
}
